import {cacheStore} from 'utils';

/**
 * action通用方法
 * @param {*} commit action中解构出的commit
 * @param {*} mutation 提交的方法名
 * @param {*} cache 是否开启缓存
 * @param {*} name? 缓存的关键字
 * @param {*} req? 请求方法
 */
function actionCommon(commit, mutation, cache, name, req) {
  const getData = () => {
    req.then(data => {
      commit(mutation, data);
      if (cache) {
        cacheStore.set(name, data);
      }
    });
  };
  if (cache) {
    const value = cacheStore.get(name);
    if (value || value === 0) {
      commit(mutation, value);
    } else {
      getData();
    }
  } else {
    getData();
  }
}

// export const mutationEvent = 'change';
export const actionEvent = 'get';
export const states = {
  test: 'string'
};
export default {
  namespaced: true,
  state: {
    test: ''
  },
  mutations: {
    changeTest(state, payload) {
      state.test = payload;
    }
  },
  actions: {
    getTest({commit}, {cache, name}) {
      // const p = new Promise(resolve => {
      //   setTimeout(() => {
      //     resolve('测试成功111111111');
      //   }, 1500)
      // }).then(data => {
      //   return `aaaaaaaaaaa${data}`
      // });
      const req = new Promise(resolve => {
        setTimeout(() => {
          resolve('测试成功111111111');
        }, 1500);
      });
      actionCommon(commit, 'changeTest', cache, name, req);
    }
  },
};
